package cn.mothin.frame.listener;

import java.lang.reflect.Method;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import cn.mothin.frame.core.exception.ErrorUrlException;
import cn.mothin.frame.core.exception.NeedLoginException;
import cn.mothin.frame.core.exception.NoPermissionException;
import cn.mothin.frame.core.interfaces.vo.IViewObject;
import cn.mothin.frame.help.PermissionRobot;

import com.opensymphony.xwork2.ModelDriven;

@Service
@Aspect
public class PermissionRobotListener {
	private final Log logger = LogFactory.getLog(PermissionRobotListener.class);
	@Autowired
	private PermissionRobot permissionRobot;

	@SuppressWarnings("unchecked")
	private IViewObject getValueObject(Object target) {
        ModelDriven<Object> model = null;
        if (target instanceof ModelDriven) {
            model = (ModelDriven<Object>) target;
        } else {
            return null;
        }
        Object obj = model.getModel();
        if(obj==null){
        	return null;
        }
        if (obj instanceof IViewObject) {
            return (IViewObject) obj;
        }
        return null;
    }
	
	@Before("execution(String cn.mothin.action..*Action.*())")
	public void checkPermission(JoinPoint jp) {
		IViewObject vo=getValueObject(jp.getTarget());
		
		Class<?> c = jp.getTarget().getClass();

		String functionName = jp.getSignature().getName();
		Method method = null;
		try {
			method = c.getMethod(functionName);
		} catch (Exception e) {
			logger.error("PermissionAspect error#A2", new ErrorUrlException());
		}

		if (!permissionRobot.needCheckPermission(method)) {
			return;
		}
		int value = permissionRobot.checkPermission(c, method,vo);
		if (value == 1) {
			throw new NeedLoginException();
		} else if (value == 2) {
			throw new NoPermissionException();
		}
	}
}
